package com.dongbo.recorder.screenrecord.ui.activity;

import android.annotation.SuppressLint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dongbo.recorder.screenrecord.base.BaseActivity;
import com.dongbo.recorder.screenrecord.utils.DateUtils;
import com.dongbo.recorder.screenrecord.widget.ResizeAbleSurfaceView;
import com.gyf.immersionbar.ImmersionBar;
import com.dongbo.recorder.screenrecord.R;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description:
 * @Author: gstory0404@gmail
 * @CreateDate: 2020/4/30 15:27
 */
public class PlayActivity extends BaseActivity {
    @BindView(R.id.paly_sv)
    ResizeAbleSurfaceView palySv;
    @BindView(R.id.paly_logo)
    ImageView palyLogo;
    @BindView(R.id.paly_start)
    ImageView palyStart;
    @BindView(R.id.paly_back)
    ImageView palyBack;
    @BindView(R.id.paly_seekbar)
    SeekBar palySeekbar;
    @BindView(R.id.paly_currentTime)
    TextView palyCurrentTime;
    @BindView(R.id.paly_allTime)
    TextView palyAllTime;

    private MediaPlayer mediaPlayer;
    private String videoPath;
    Disposable disposable;

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!TextUtils.isEmpty(videoPath)) {
            palyStart.setVisibility(View.VISIBLE);
            palyLogo.setVisibility(View.VISIBLE);
            Glide.with(this).load(videoPath).into(palyLogo);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_play;
    }

    @Override
    protected void initView() {
        ImmersionBar
                .with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.black)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initData() {
        videoPath = getIntent().getStringExtra("videoPath");
        Glide.with(this).load(videoPath).into(palyLogo);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initListener() {
        palySv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    play();
                }
                return true;
            }
        });

    }

    public void play() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    //重置
                    palySeekbar.setProgress(0);
                    palyCurrentTime.setText("00:00");
                    palyStart.setVisibility(View.VISIBLE);
                    if (disposable != null) {
                        disposable.dispose();
                        disposable = null;
                    }
                }
            });
            //设置类型
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            palySv.resize(1080, 1920);
//            int width = (int) FFmpegCommand.getInfoSync(videoPath, Attribute.WIDTH);
//            int height = (int) FFmpegCommand.getInfoSync(videoPath, Attribute.HEIGHT);
//            palySv.resize(width, height);
            try {
                /* 为MediaPlayer 设置数据源 */
                mediaPlayer.setDataSource(videoPath);
                /* 准备 */
                mediaPlayer.prepare();
                //将播放器捕捉的画面展示到SurfaceView画面上
                mediaPlayer.setDisplay(palySv.getHolder());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            palyLogo.setVisibility(View.GONE);
            mediaPlayer.start();
            //获取总时长
            int duration = mediaPlayer.getDuration();
            palySeekbar.setMax(duration);
            palyAllTime.setText(DateUtils.longToDate(duration));
            disposable = Observable.interval(100, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (mediaPlayer != null
                                    && palySeekbar.getProgress() <= palySeekbar.getMax() - 1) {
                                //获取当前位置音乐播放的位置
                                int currentPosition = mediaPlayer.getCurrentPosition();
                                palySeekbar.setProgress(currentPosition);
                                palyCurrentTime.setText(DateUtils.longToDate(currentPosition));
                                palyStart.setVisibility(View.GONE);
                            }
                        }
                    });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    palyStart.setVisibility(View.VISIBLE);
                    palyLogo.setVisibility(View.VISIBLE);
                    Glide.with(PlayActivity.this).load(videoPath).into(palyLogo);
                }
            });
        } else if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            palyStart.setVisibility(View.VISIBLE);
            if (disposable != null) {
                disposable.dispose();
                disposable = null;
            }
        } else {
            palyLogo.setVisibility(View.GONE);
            mediaPlayer.setDisplay(palySv.getHolder());
            mediaPlayer.start();
            palyStart.setVisibility(View.GONE);
            disposable = Observable.interval(100, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (mediaPlayer != null
                                    && mediaPlayer.isPlaying()
                                    && palySeekbar.getProgress() <= palySeekbar.getMax() - 1) {
                                //获取当前位置音乐播放的位置
                                int currentPosition = mediaPlayer.getCurrentPosition();
                                palySeekbar.setProgress(currentPosition);
                                palyCurrentTime.setText(DateUtils.longToDate(currentPosition));
                                palyStart.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    }

    @OnClick({R.id.paly_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.paly_back:
                finish();
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }
        if (disposable != null) {
            disposable.dispose();
            disposable = null;
        }
    }
}
